package com.taobao.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.taobao.api.TaobaoApiException;
import com.taobao.api.direct.TaobaoDirectJsonRestClient;
import com.taobao.api.extra.model.TradeAddRequest;
import com.taobao.api.extra.model.TradeAddResponse;
import com.taobao.api.model.DeliverySendRequest;
import com.taobao.api.model.DeliverySendResponse;
import com.taobao.api.model.Order;
import com.taobao.api.model.Trade;
import com.taobao.api.model.TradeMemoAddRequest;
import com.taobao.api.model.TradeMemoAddResponse;
import com.taobao.api.model.TradesBoughtGetRequest;
import com.taobao.api.model.TradesGetResponse;
import com.taobao.api.model.TradesSoldGetRequest;
import com.taobao.client.obj.TopItem;
import com.taobao.client.obj.TopOrder;
import com.taobao.client.obj.TopTrade;

/**
 * 
 * @author hujingfei.pt@taobao.com
 *
 */
public class TradeService {

	int size = 100;
	private String TRADES_BOUGHT_FIELDS_STRING = "pic_path,price,tid,seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,orders,consign_time,"
			+ "total_fee,discount_fee,adjust_fee,discount_fee,adjust_fee,post_fee,sid,out_sid,pay_time,end_time,modified,buyer_obtain_point_fee,"
			+ "point_fee,real_point_fee";

	private TaobaoDirectJsonRestClient c;
	private UpperServiceImpl g;
	public static final String TYPE = "shopex_trade";// "shopex_trade";//"independent_shop_trade";

	/**
	 * Constructor.
	 * 
	 * @param c
	 * @param greetingServiceImpl
	 */
	public TradeService(TaobaoDirectJsonRestClient c,
			UpperServiceImpl greetingServiceImpl) {
		this.c = c;
		g = greetingServiceImpl;
	}

	/**
	 * 
	 * @param sessionid
	 * @param nick
	 * @return
	 * @throws Exception
	 */
	public List<TopTrade> testTradesSoldGetByFields(String sessionid,
			String nick) throws Exception {
		TradesSoldGetRequest tradesSoldGetRequest = new TradesSoldGetRequest();
		tradesSoldGetRequest.setFields(TRADES_BOUGHT_FIELDS_STRING);
		tradesSoldGetRequest.setType(TYPE);

		tradesSoldGetRequest.setPageSize(size);
		TradesGetResponse tradesGetResponse = c.tradesSoldGet(
				tradesSoldGetRequest, sessionid, nick);

		g.processError(tradesGetResponse);

		List<Trade> trades = tradesGetResponse.getTrades();

		return fetchTopTrade(trades);
	}

	/**
	 * Return a list of top trades from a list of trades
	 * 
	 * @param trades
	 *            Trade list to be transfered
	 * @return A list of top trades
	 */
	private List<TopTrade> fetchTopTrade(List<Trade> trades) {
		List<TopTrade> trs = new ArrayList<TopTrade>();
		if (trades != null) {
			for (Trade t : trades) {
				TopTrade tr = new TopTrade();
				try {
					List<Order> orders = t.getOrders();
					List<TopOrder> tos = new ArrayList<TopOrder>();
					for (Order o : orders) {
						TopOrder or = new TopOrder();
						BeanUtils.copyProperties(or, o);
						tos.add(or);
					}
					BeanUtils.copyProperties(tr, t);
					tr.setTopOrders(tos);
					trs.add(tr);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return trs;
	}

	/**
	 * 
	 * @param nick
	 *            The nick name of the buyer
	 * @return A list of top trades
	 * @throws Exception
	 */
	public List<TopTrade> tradeBoughtGet(String nick) throws Exception {
		// Obtain an encapsulated request object of getting bought trades
		TradesBoughtGetRequest tradesRequest = new TradesBoughtGetRequest();
		// Fields which will have value in the resulting trade object
		String fields = "seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,"
				+ "buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,pay_time,"
				+ "end_time,consign_time,modified,buyer_obtain_point_fee,point_fee,real_point_fee,"
				+ "received_payment,pic_path,iid,num,price,cod_fee,shipping_type,alipay_no,orders";
		tradesRequest.setFields(fields);

		final int pageSize = 100;
		tradesRequest.setPageSize(pageSize);
		tradesRequest.setType(TYPE);

		try {
			// Return a response object through which data can be fetched
			TradesGetResponse tradesBoughtGet = c.tradesBoughtGet(
					tradesRequest, g.getSession(), nick);
			// Handle errors such as service unavailable and invalid session and
			// so on
			g.processError(tradesBoughtGet);

			List<Trade> tradeList = tradesBoughtGet.getTrades();

			int page = 1;
			while (tradeList.size() < tradesBoughtGet.getTotalResults()) {
				tradesRequest.setPageNo(page++);
				tradesBoughtGet = c.tradesBoughtGet(tradesRequest, g
						.getSession(), nick);
				tradeList.addAll(tradesBoughtGet.getTrades());
			}

			// A new TopTrade list
			List<TopTrade> topTradeList = fetchTopTrade(tradeList);
			return topTradeList;
		} catch (TaobaoApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param item
	 *            The item covered in the trade
	 * @param buyer
	 *            Buyer name
	 * @param seller
	 *            Seller name
	 * @param isNewAddress
	 * @throws Exception
	 */
	public void addTrade(List<TopItem> items, String buyer, String seller,
			String name, String phone, String mobile, String province,
			String city, String area, String division_code, String post_code,
			String address_detail, boolean isNewAddress, String memos,
			String discount) throws Exception {
		try {

			TradeAddRequest request = new TradeAddRequest();

			System.out.println("addTrade:address = " + isNewAddress);

			String skuIds = "";
			String titles = "";
			String iids = "";
			String prices = "";
			String nums = "";
			// String memos = "";

			for (TopItem i : items) {
				titles += i.title + ",";
				iids += i.iid + ",";
				prices += i.price + ",";
				nums += "1,";
				// memos += "SHOPEX MEMO,";
			}

			request.setSaveDeliverAddr(isNewAddress);
			request.setDiscountFees(discount
					.substring(0, discount.length() - 1));
			request.setTitles(titles.substring(0, titles.length() - 1));
			request.setIids(iids.substring(0, iids.length() - 1));
			request.setPrices(prices.substring(0, prices.length() - 1));

			if (skuIds.length() > 0)
				request.setSkuIds(skuIds.substring(0, skuIds.length() - 1));
			else
				request.setSkuIds("");

			request.setNums(nums.substring(0, nums.length() - 1));
			request.setSellerNick(seller);
			request.setLocationZip("123456");
			request.setPostFee("123.12");
			request.setDivisionCode(division_code);
			request.setLocationAddress(address_detail);
			request.setSnapshot("jeck snapshot1");
			Map<String, String> orderSnap = new HashMap<String, String>();

			for (TopItem i : items) {
				String sku = "";
				if (i.topSku != null && i.topSku.size() > 0)
					sku += i.topSku.get(0).skuId;

				orderSnap
						.put("snapshot_" + i.iid + "_" + sku, "jeck snapshot2");
			}

			request.setOrderSnapshots(orderSnap);
			request.setLogisticType("express");

			request.setType(TYPE);
			request.setSnapshot("snapshot");

			request.setPostFee("5");
			request.setDivisionCode(division_code);
			request.setLocationZip("123456");

			System.out.println("discount = " + request.getDiscountFees());
			System.out.println("address_detail = " + address_detail);
			System.out.println("city = " + city);
			System.out.println("province = " + province);
			System.out.println("area = " + area);
			System.out.println("name = " + name);
			
			System.out.println("iids = " + iids);

			request.setLocationAddress(address_detail);
			request.setLocationCity(city);
			request.setLocationState(province);
			request.setLocationDistrict(area);
			request.setReceiverName(name);
			request.setPhone(phone);
			request.setMobile(mobile);
			request.setOrderMemos(memos.substring(0, memos.length() - 1));
			
			System.out.println("memo = " + request.getOrderMemos());
			
			try {
				TradeAddResponse tradeAddResponse = c.tradeAdd(request, g
						.getSession(), g.getLoginName());
				g.processError(tradeAddResponse);
			} catch (TaobaoApiException e) {
				throw new Exception(e.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 创建订单memo
	 * @param memo
	 * @param tid
	 * @throws Exception
	 */
	public void addTradeMemo(String memo, String tid) throws Exception {
		TradeMemoAddRequest req = new TradeMemoAddRequest();
		req.setTid(tid);
		req.setMemo(memo);

		TradeMemoAddResponse rsp;
		try {
			rsp = c.tradeMemoAdd(req, g.getSession(), g.getLoginName());
			g.processError(rsp);
		} catch (TaobaoApiException e) {
			e.printStackTrace();
			throw new Exception("调用系统出错,错误原因:"+e.getMessage());
		}
	}

	/**
	 * 
	 * @param tid
	 *            Id of the trade
	 * @throws Exception
	 */
	public void deliverySend(String tid) throws Exception {
		DeliverySendRequest req = new DeliverySendRequest();
		req.setTid(tid);
		req.setOrderType("virtual_goods");

		// DeliverySendRequest req = new DeliverySendRequest();
		// req.setTid(tid); //交易IDtaobao.trades.sold.get
		// req.setCompanyCode("EMS"); //可以通过taobao.logisticcompanies.get查询物流公司代码
		// req.setMemo("test"); //卖家备注
		// req.setOutSid("CA123456789CN"); //运单号 具体一个物流公司的运单号码
		// req.setSellerAddress("北街接待办事处"); //卖家地址(详细地址)省、市、区不需要提供
		// req.setSellerAreaId("110101"); //卖家所在地国家公布标准地区码通过taobao.areas.get获取
		// req.setSellerMobile("13569874563");
		// req.setSellerName("张三");
		// req.setSellerPhone("0571-12345678");
		// req.setSellerZip("101021");

		DeliverySendResponse deliverySend = c.deliverySend(req, g.getSession(),
				g.getLoginName());
		g.processError(deliverySend);
	}
}
